package dicTree;

public class ImplementTriePrefixTree208 {
    class Node {
        public boolean end;
        public Node[] child = new Node[26];

        public Node(boolean end) {
            this.end = end;
        }
    }

    /**
     * Initialize your data structure here.
     */

    Node root;

    public ImplementTriePrefixTree208() {
        root = new Node(false);
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        Node temp = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (temp.child[c - 'a'] == null) {
                Node node = new Node(false);
                temp.child[c - 'a'] = node;
            } else {
            }
            temp = temp.child[c - 'a'];
            if(i==word.length()-1){
                temp.end = true;
            }
        }

    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        Node temp = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (temp.child[c - 'a'] == null) {
                return false;
            }
            temp = temp.child[c - 'a'];
            if(i==word.length()-1&&temp.end){
                return true;
            }
        }
        return false;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        Node temp = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (temp.child[c - 'a'] == null) {
                return false;
            }
            temp = temp.child[c - 'a'];

        }
        return true;
    }
}
